package com.githan.bootsecurity.service;

import cn.hutool.core.util.StrUtil;
import com.githan.bootsecurity.entity.SysUser;
import com.githan.bootsecurity.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author https://github.com/Han56
 * @date 2021/4/10 14:34
 */
@Service(value = "userDetailsService")
public class UserDetailServiceImp implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StrUtil.isEmpty(username)){
            throw  new  RuntimeException("用户名不能为空");
        }
        //如果不为空则根据用户名获取用户信息
        SysUser sysUser = sysUserMapper.getOneUserInfo(username);
        if (sysUser == null){
            throw new UsernameNotFoundException(String.format("%s这个用户不存在",username));
        }
        //如果存在则赋予用户权限集
        List<GrantedAuthority> authorityList = new ArrayList<>();
        List<String> codeList = sysUserMapper.getRoleCodeByusername(username);
        //需要根据用户获取角色   根据登陆的用户获取权限/角色集合
        codeList.forEach(code->{
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(code);
            authorityList.add(authority);
        });
        return new User(sysUser.getUsername(),sysUser.getPassword(),authorityList);
    }
}
